﻿using Common.Utility;
using Domain.Sys;
using DTO;
using IServices;
using IServices.Sys;
using log4net;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Web.Filter;

namespace Web.Controllers
{
    public class LoginController : BaseController
    {
        #region 初始化

        private readonly IAdminUserService _service;
        public LoginController(IAdminUserService service)
        {
            _service = service;
        }
        #endregion

        [NoLogin]
        public async Task<IActionResult> Index()
        {
            return View();
        }

        [NoLogin]
        [HttpPost]
        public async Task<Result> Login(string username, string password)
        {
            password = SHAEncrypt.SHA256(password);
            AdminUser user = await _service.GetByUserNameAsync(username);
            if (user == null)
            {
                return Result.Failed(-1, "用户名不存在！");
            }
            if (user.Password != password)
            {
                return Result.Failed(-1, "密码不正确！");
            }
            var cookievalue = user.Id + "|" + user.UserName + "|" + user.SurName + "|" + user.IsAdmin;


            var claims = new List<Claim>() //用Claim保存用户信息
            {
                new Claim(ClaimTypes.Name,user.SurName),
                new Claim("Id",user.Id),
                new Claim("UserName",user.UserName),
                new Claim("IsAdmin",user.IsAdmin.ToString()),
            };

            //把用户信息装到ClaimsPrincipal
            ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Admin"));
            //登录，把用户信息写入到cookie
            HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal,
                new AuthenticationProperties
                {
                    ExpiresUtc = DateTime.Now.AddDays(2)
                }).Wait();

            return Result.Success("登录成功");
        }


        [NoPermission]
        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return RedirectToAction("Index", "Login");
        }

    }
}